package org.wenhua.yuan.and.views.tab;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.wenhua.yuan.R;
import org.wenhua.yuan.and.util.DisplayConvert;
import org.wenhua.yuan.and.views.tab_fragment.TabBtnFragmentLayout;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 自定义布局控件 - 底部导航栏
 * @TabBtnBottom 单个Tab按钮
 * @TabBtnBottomInfo 单个Tab按钮的实体
 * @TabBtnBottomInfo<?> 中泛型不能具体到类型
 */
public class TabBtnLayoutBottomNav extends FrameLayout
        implements ITabLayout<TabBtnBottom, TabBtnBottomInfo<?>>{

    private List<TabBtnBottomInfo<?>> tabInfoList;
    private List<OnTabSelectedListener<TabBtnBottomInfo<?>>> listenerList = new ArrayList<>();
    private TabBtnBottomInfo<?> selectedTabBtn; // 声明当前被选中的tab
    private final String bottomLineColor = "#dfe0e1";
    private final String TAG = "FrameLayout-cur-tag"; // 定义当前布局控件标识

    private final int NAV_HEIGHT = 48; // 生命底部导航栏的布局dp高度

    public TabBtnLayoutBottomNav(@NonNull Context context) {
        this(context,null);
    }

    public TabBtnLayoutBottomNav(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TabBtnLayoutBottomNav(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initTabBtnLayoutBottomNav(context, attrs, defStyleAttr);
    }

    private void initTabBtnLayoutBottomNav(Context context, AttributeSet attrs, int defStyleAttr) {

        /**未使用*/
    }

    @Override
    public TabBtnBottom findTab(@NonNull TabBtnBottomInfo<?> dataInfo) {
        // 获取当前布局实例，通过实例遍历布局ViewGroup(TabBtnLayoutBottomNav)中的子ViewGroup（TabBtnBottom）
        // 通过TabBtnBottom 获取自己的TabBtnBottomInfo,然后比对，从而获取TabBtnBottom。
        FrameLayout frameLayout = findViewWithTag(TAG);
        int count = frameLayout.getChildCount();
        for (int i = 0; i < count; i ++) {
            View child = frameLayout.getChildAt(i);
            if (child instanceof TabBtnBottom) {
                TabBtnBottom tabBtnBottom = (TabBtnBottom) child;
                if (tabBtnBottom.getTabBtnBottomInfo() == dataInfo) {
                    return tabBtnBottom;
                }
            }
        }

        return null;
    }

    /** 对当前TabBtnLayoutBottomNav，添加监听的方法。回调被点击tab信息。*/
    @Override
    public void addTabSelectedChangeListener(OnTabSelectedListener<TabBtnBottomInfo<?>> listener) {
        listenerList.add(listener);
    }

    @Override
    public void defaultSelected(@NonNull TabBtnBottomInfo<?> defaultInfo) {
        toSelected(defaultInfo);
    }

    private void toSelected(TabBtnBottomInfo<?> btnBottomInfo) {
        for (OnTabSelectedListener<TabBtnBottomInfo<?>> selectedListener : listenerList) {
            int index = tabInfoList.indexOf(btnBottomInfo);
            selectedListener.onTabSelectedListener(index, this.selectedTabBtn, btnBottomInfo);
        }

        this.selectedTabBtn = btnBottomInfo;// 记录当前被选中的按钮
    }

    @Override
    public void inflateInfo(@NonNull List<TabBtnBottomInfo<?>> listInfo) {
        if (listInfo.isEmpty()) return;
        this.tabInfoList = listInfo;

        this.selectedTabBtn = null;

        clearTabBtnBottomAddedEarly(); // 移除添加过的tab
        addFragmentLayout(); // 添加fragment布局控件
        addBackground();// 添加背景色
        clearTabBtnBottomOnTabSelectedListenerAddedEarly(); // 清除监听List<OnTabSelectedListener<TabBtnBottomInfo<?>>>集合之前添加的TabBtnBottom
        FrameLayout frameLayout = addTabBtnBottomAllInFrameLayout(); // 添加所有的TabBtnBottom到布局中
        addBottomLine(); // 先添加分割线，再排布tab
        LayoutParams param = new LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        param.gravity = Gravity.BOTTOM;
        addView(frameLayout,param); // 将tab所在的FrameLayout放置在Z轴最外层
    }

    private void addFragmentLayout() {

        TabBtnFragmentLayout fragmentLayout = new TabBtnFragmentLayout(getContext());
        fragmentLayout.setId(R.id.fragmentTabLayout);
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        addView(fragmentLayout, params);
    }

    /**
     * 获取fragment自定义布局控件
     * @return
     */
    public TabBtnFragmentLayout getTabBtnFragmentLayout() {
        return findViewById(R.id.fragmentTabLayout);
    }

    private void addBottomLine() {
        View bottomLine = new View(getContext());
        bottomLine.setBackgroundColor(Color.parseColor(bottomLineColor));
        LayoutParams param = new LayoutParams(LayoutParams.MATCH_PARENT, DisplayConvert.dp2px(1, getResources()));
        param.gravity = Gravity.BOTTOM;
        int marginBottom = DisplayConvert.dp2px(NAV_HEIGHT-3, getContext().getResources());
        param.bottomMargin = marginBottom;
        addView(bottomLine, param);
        bottomLine.setAlpha(1f);
    }

    private FrameLayout addTabBtnBottomAllInFrameLayout() {
        FrameLayout layout = new FrameLayout(getContext());
        layout.setTag(TAG);

        int tabHeight = DisplayConvert.dp2px(NAV_HEIGHT, getContext().getResources());
        int tabWidth = DisplayConvert.getDisplayWidthInPx(getContext())/tabInfoList.size();

        for (int i = 0; i < tabInfoList.size(); i++) {

            final TabBtnBottom btnBottom = new TabBtnBottom(getContext());
            listenerList.add(btnBottom); // 添加到监听list
            btnBottom.setTabInfo(tabInfoList.get(i));
            btnBottom.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    toSelected(btnBottom.getTabBtnBottomInfo());
                }
            });
            LayoutParams param = new LayoutParams(tabWidth, tabHeight);
            param.gravity = Gravity.BOTTOM;
            param.leftMargin = i * tabWidth;
            layout.addView(btnBottom, param);
        }

        layout.bringToFront();
        return layout;
    }
    private void clearTabBtnBottomAddedEarly() {
        int count = getChildCount() - 1;
        for (int i = count; i > 0; i--) {
            removeViewAt(i);
        }
    }

    private void clearTabBtnBottomOnTabSelectedListenerAddedEarly() {
        Iterator<OnTabSelectedListener<TabBtnBottomInfo<?>>> iterator = listenerList.iterator();
        while (iterator.hasNext()) {
            // 避免删除TabBtnLayoutBottomNav的监听
            if (iterator.next() instanceof TabBtnBottom) {
                iterator.remove();
            }
        }

    }

    private void addBackground() {
        View viewbg = LayoutInflater.from(getContext()).inflate(R.layout.bg_tab_layout, null);
        LayoutParams param = new LayoutParams(LayoutParams.MATCH_PARENT, DisplayConvert.dp2px(45, getContext().getResources()));
        param.gravity = Gravity.BOTTOM;
        addView(viewbg, param);
        viewbg.setAlpha(1f);
    }

}
